package com.wn.icloud.common.utils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;

import java.io.*;
import java.net.URLEncoder;

import static org.apache.commons.codec.binary.StringUtils.newString;

/**
 * @author: zhq
 * @datetime: 2019/11/20 17:45
 * @description: TODO
 */
public class UploadUtil {

public static String serviceAddress = "ftp://114.116.121.16";
private static String hostname = "114.116.121.16";
private static String username = "anonymous";
private static String password = "";
private static String ftpWorkPath = "/upload";

    //设置为被动模式,上传至ftp服务器
    public static String uploadFtpFile(InputStream input, String fileName){
        FTPClient ftpClient = new FTPClient();
        FileInputStream fis = null;
        try {
            ftpClient.connect(hostname);
            ftpClient.login(username, password);
            /*设置上传目录 */
            ftpClient.changeWorkingDirectory("/" + ftpWorkPath);
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("UTF-8");
            /*设置为被动模式*/
            ftpClient.enterLocalPassiveMode();
            /*设置文件类型（二进制） */
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //设置中文名不出现乱码
            ftpClient.storeFile(new String(fileName.getBytes("UTF-8"),"iso-8859-1"), input);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("FTP客户端出错！", e);
        } finally {
            IOUtils.closeQuietly(fis);
            disconnect(ftpClient);
            System.out.println("已上传至FTP服务器路径！");
        }
        return ftpWorkPath + "/" + fileName;
    }

    //启动客户端
    public static FTPClient startFtpClient(FTPClient ftpClient) throws IOException{

            ftpClient.connect(hostname);
            ftpClient.login(username, password);
            //设置缓冲区上传速度为10M，默认为1K
            ftpClient.setBufferSize(1024 * 1024 * 10);
            //设置编码
            ftpClient.setControlEncoding("UTF-8");
            /*设置为被动模式*/
            ftpClient.enterLocalPassiveMode();
            /*设置文件类型（二进制） */
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            return ftpClient;
    }

    /**
     * 下载ftp文件到本地上
     *
     * @param ftpFileName ftp文件路径名称
     * @param localFile   本地文件路径名称
     */
    public static void download(String ftpFileName, File localFile) throws IOException {
        OutputStream out = null;
        FTPClient ftpClient = startFtpClient(new FTPClient());
        try {
            //ftpClient.configure(new FTPClientConfig("com.zznode.tnms.ra.c11n.nj.resource.ftp.UnixFTPEntryParser"));
            FTPClientConfig config = new FTPClientConfig(ftpClient.getSystemType().split(" ")[0]);
            config.setServerLanguageCode("zh");
            ftpClient.enterLocalPassiveMode();
            System.out.println("----------------------------------------------**********************************-OS1");
            FTPFile[] fileInfoArray = ftpClient.listFiles(ftpFileName);
            if (fileInfoArray == null || fileInfoArray.length == 0) {
                System.out.println("----------------------------------------------**********************************-OS2");
                throw new FileNotFoundException("File " + ftpFileName + " was not found on FTP server.");
            }
            FTPFile fileInfo = fileInfoArray[0];
            if (fileInfo.getSize() > Integer.MAX_VALUE) {
                throw new IOException("File " + ftpFileName + " is too large.");
            }
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            if (!ftpClient.retrieveFile(ftpFileName, out)) {
                throw new IOException("Error loading file " + ftpFileName + " from FTP server. Check FTP permissions and path.");
            }
            out.flush();
        } finally {
            closeStream(out);
            disconnect(ftpClient);
        }
    }

    /**
     * 获取ftp上指定文件名到输出流中
     *
     * @param ftpFileName 文件在ftp上的路径  如绝对路径 /home/ftpuser/123.txt 或者相对路径 123.txt
     * @param out         输出流
     */
    public static void retrieveFile(String ftpFileName, OutputStream out) throws IOException {
        FTPClient ftpClient = startFtpClient(new FTPClient());
        try {
            ftpClient.setControlEncoding("UTF-8");
            /*设置为被动模式*/
            ftpClient.enterLocalPassiveMode();
            /*设置文件类型（二进制） */
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //设置中文名不出现乱码
            FTPFile[] fileInfoArray = ftpClient.listFiles(new String(ftpFileName.getBytes("UTF-8"),"ISO-8859-1"));
            if (fileInfoArray == null || fileInfoArray.length == 0) {
                throw new FileNotFoundException("File '" + ftpFileName + "' was not found on FTP server.");
            }
            FTPFile fileInfo = fileInfoArray[0];
            if (fileInfo.getSize() > Integer.MAX_VALUE) {
                throw new IOException("File '" + ftpFileName + "' is too large.");
            }
            if (!ftpClient.retrieveFile(new String(ftpFileName.getBytes("UTF-8"),"ISO-8859-1"), out)) {
                throw new IOException("Error loading file '" + ftpFileName + "' from FTP server. Check FTP permissions and path.");
            }
            out.close();
        } finally {
            closeStream(out);
            disconnect(ftpClient);
        }
    }

    /**
     * 关闭流
     *
     * @param stream 流
     */
    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException ex) {
                // do nothing
            }
        }
    }

    /**
     * 关闭ftp连接
     */
    private static void disconnect(FTPClient ftpClient) {
        if (null != ftpClient && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException ex) {
                // do nothing
            }
        }
    }
}
